"""
功能描述：实现邮件的配置，和对外提供发送邮件的方法
编写人：lc
编写日期：
实现逻辑：
    1、导包
    2、配置邮箱属性
    3、组装邮件内容和标题、附件
    4、连接登录并发送
"""
import smtplib ,time,os
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.header import Header

class sendexcel():
    def __init__(self):
        self.sender='825622958@qq.com'
        self.receiver='825622958@qq.com'
        t=time.strftime("%Y-%m-%d %H:%M:%S",time.localtime())
        self.subject='自动化测试结果_'+t
        self.smtpserver='smtp.qq.com'
        self.username='825622958@qq.com'
        self.password='dfgtfujqrceqbbgd'

    def __config(self, file):
        # 第二步：准备附件，增加附件，组装邮件内容和标题
        # 读取html文件内容
        with open(file, 'rb') as f:
            mail_body = f.read()
            # 组装邮件内容和标题
            self.msg = MIMEMultipart()
            # 添加附件内容
            att = MIMEText(mail_body, 'plain', 'utf-8')
            att["Content-Type"] = 'application/octet-stream'
            att["Content-Disposition"] = 'attachment; filename=report.html'
            self.msg.attach(att)
            # 添加邮件的文本内容
            content = '自动化测试报告详情，请查收附件'
            self.msg.attach(MIMEText(content, 'plain', 'utf-8'))
            self.msg['Subject'] = Header(self.subject, 'utf-8')
            self.msg['From'] = self.sender
            self.msg['To'] = self.receiver

    def send(self,file):
        self.__config(file)
        try:
            smtp=smtplib.SMTP()
            smtp.connect(self.smtpserver)
            smtp.login(self.username,self.password)
            smtp.sendmail(self.sender,self.receiver,self.msg.as_string())
        except Exception as msg:
            print("邮件发送失败！%s" % msg)
        else:
            print("邮件发送成功！")
        finally:
            smtp.quit()

if __name__ == '__main__':
    ce =sendexcel()
    ce.send()